package com.lambkit.plugin.groovy;

import com.lambkit.core.script.IScriptEngine;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.codehaus.groovy.runtime.InvokerHelper;

import java.util.Map;

/**
 * @author yangyong(孤竹行)
 */
public class GroovyScriptEngine implements IScriptEngine {
    @Override
    public Object invoke(String scriptText, Map<String, Object> context) throws Exception {
        Binding binding = new Binding();
        for (String key : context.keySet()) {
            binding.setProperty(key, context.get(key));
        }
        GroovyShell groovyShell = new GroovyShell(binding);
        return groovyShell.evaluate(scriptText);
    }

    @Override
    public Object invokeMethod(String scriptText, String functionName, Map<String, Object> context) throws Exception {
        GroovyShell groovyShell = new GroovyShell();
        Script script= groovyShell.parse(scriptText);
        return InvokerHelper.invokeMethod(script, functionName, new Object[]{context});
    }
}
